package com.dzx.currentency.commonUnSafe;

import com.dzx.currentency.annoations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.text.SimpleDateFormat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author DuanZhaoXu
 * @ClassName:
 * @Description:
 * @date 2018年11月17日 14:46:52
 */
@Slf4j
@NotThreadSafe
public class StringExample1 {

    //请求次数
    private static int clientTotal = 5000;

    //允许同时运行的线程数
    private static int threadTotal = 200;

    /**
     * stringBuilder 线程不安全
     * stringBuffer 线程安全
     */
    //public static  StringBuilder stringBuilder=new StringBuilder();
    public static StringBuffer stringBuffer = new StringBuffer();

    /**
     * simpleDateFormat 不是线程安全的
     * joda-time 的dateTimeFormatter 是线程安全的
     */
    public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");

    public static DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy/MM/dd");

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    append();
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });

        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        log.info("count:{}", stringBuffer.length());
    }

    private static void append() {
        DateTime dateTime = DateTime.parse("2018/06/07", dateTimeFormatter);
        log.info(dateTime.toDate().toString());
    }
}

